using System;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DotPulsar.Abstractions;
using tafei_thingsapi.Utils;
namespace tafei_thingsapi.Services.auth
{
    public class IoTAuthentication : IAuthentication
    {
        private string token;
        public IoTAuthentication(string iotAccessId, string iotSecretKey)
        {
            Console.WriteLine("iotAccessId={0} iotSecretKey={1}",iotAccessId,iotSecretKey);
            string password = SecurityUtils.Sha256Hex(iotAccessId + SecurityUtils.Sha256Hex(iotSecretKey)).Substring(4, 16);

            token = $"{{\"tenant\":\"{iotAccessId}\",\"password\":\"{password}\"}}";
        }
        private string methodName = "iot-auth";

        public string AuthenticationMethodName => methodName;

        public ValueTask<byte[]> GetAuthenticationData(CancellationToken cancellationToken)
        {
            return ValueTask.FromResult(Encoding.UTF8.GetBytes(token));
        }
    }

    public class Hex
    {
        /// <summary>
        /// 字节数组转换为Hex字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="toLowerCase"></param>
        /// <returns></returns>
        public static string ByteArrayToHexString(byte[] data, bool toLowerCase = true)
        {
            var hex = BitConverter.ToString(data).Replace("-", string.Empty);
            return toLowerCase ? hex.ToLower() : hex.ToUpper();
        }
    }
    public class DigestUtils
    {
        /// <summary>
        /// SHA256 转换为 Hex字符串
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Sha256Hex(string data)
        {
            var bytes = Encoding.UTF8.GetBytes(data);
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(bytes);
                return Hex.ByteArrayToHexString(hash);
            }
        }

        /// <summary>
        /// SHA256 转换为 Hex字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Sha256Hex(string data, Encoding encoding)
        {
            var bytes = encoding.GetBytes(data);
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(bytes);
                return Hex.ByteArrayToHexString(hash);
            }
        }

        /// <summary>
        /// SHA256 转换为 Hex字符串
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string Sha256Hex(byte[] bytes)
        {
            using (var sha256 = SHA256.Create())
            {
                var hash = sha256.ComputeHash(bytes);
                return Hex.ByteArrayToHexString(hash);
            }
        }
    }

}